package com.zhongyouyun.admin.controller;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.alicp.jetcache.Cache;
import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhongyouyun.admin.mapper.UserMapper;
import com.zhongyouyun.admin.model.DeptModel;
import com.zhongyouyun.admin.model.RoleModel;
import com.zhongyouyun.admin.model.UserModel;
import com.zhongyouyun.admin.service.DeptService;
import com.zhongyouyun.admin.service.RoleService;
import com.zhongyouyun.admin.vo.UserVo;
import com.zhongyouyun.config.RedisConfig;
import com.zhongyouyun.other.annotation.SysLogAnnotation;
import com.zhongyouyun.other.model.Result;
import com.zhongyouyun.other.model.TokenUtil;
import com.zhongyouyun.utils.LongUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/admin/login")
@Api(value = "登录controller", tags = {"登录接口"})
public class LoginController {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisConfig redisConfig;
    @Resource
    private RoleService roleService;
    @Resource
    private DeptService deptService;
//    @CreateCache(name="jetCache_",expire = 10,timeUnit = TimeUnit.SECONDS)
//    private Cache<String ,String> jetCache;

    /**
     * 登录
     *
     * @param userModel 用户实体类
     * @return
     */
    @PostMapping("/ajaxLogin")
    @ResponseBody
    @ApiOperation(value = "登录", notes = "登录")
    @SysLogAnnotation(operModul = "系统管理>>登录", operType = "登录", operDesc = "登入后台管理平台")
    public Result submitLogin(@RequestBody UserModel userModel, HttpServletRequest request) throws Exception {

        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.getSession().getId());
//        if (subject.getPrincipal() != null) {
//            String msg2 = "同一个浏览器同时只能一个账号登录，请退出前一个账号后再重试";
//            System.out.println(subject.getSession().getId());
//            return Result.builder().message(msg2).status(1).success(false).data(resultMap).build();
//        } else {
            QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
            userModelQueryWrapper.eq("user_name", userModel.getUserName());
            userModelQueryWrapper.eq("password", SecureUtil.md5(userModel.getPassword()));
            UserModel user = userMapper.selectOne(userModelQueryWrapper);
            if (ObjectUtil.isNotEmpty(user)) {
                if ("0".equals(user.getState())) {
                    return Result.builder().message("账号已锁定").status(1).success(false).data(resultMap).build();
                } else {
                    if (ObjectUtil.isNotNull(user)) {
                        user.setType("1");
                        if (ObjectUtil.isNotEmpty(user.getRoleId())) {
                            List<RoleModel> roleModelList = roleService.selectbyList( LongUtil.Longva(user.getRoleId().split(",")));
                            boolean present = roleModelList.stream().filter(m -> "0".equals(m.getType())).findAny().isPresent();//是否有户主
                            if (present) {
                                user.setType("0");
                            }
                        }
                        UsernamePasswordToken token = new UsernamePasswordToken("user_" + user.getId().toString(), user.getPassword(), true);
                        subject = SecurityUtils.getSubject();
                        subject.login(token);
                        user.setPassword(null);
                        resultMap.put("user", user);
                        String u_token = TokenUtil.getToken(user.getUserName() + "_" + user.getId(), subject.getSession().getId().toString(), token.getHost());
                        redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
                        user.setActivation("1");
                        userMapper.updateById(user);
                        resultMap.put("token", u_token);
                        resultMap.put("type", user.getType());
                        return Result.builder().message("登录成功").status(0).data(resultMap).build();
                    } else {
                        return Result.builder().message("账号密码错误").status(1).success(false).data(resultMap).build();
                    }
                }
            } else {
                return Result.builder().message("账号密码错误").status(1).success(false).data(resultMap).build();
            }
//        }
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户信息刷新token时间", notes = "获取用户信息刷新token时间")
    public Result getUser() {
        Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
        Subject subject = SecurityUtils.getSubject();
        Object u = subject.getPrincipal();
        if (u instanceof UserModel) {
            UserModel user = (UserModel) subject.getPrincipal(); // 获取当前登录用户
            resultMap.put("user", user);
            resultMap.put("type", user.getType());
            String u_token = (String) redisConfig.get(subject.getSession().getId().toString());
            redisConfig.set(subject.getSession().getId().toString(), u_token, 60 * 60 * 60 * 2L);
            return Result.builder().message("获取成功").status(0).success(true).data(resultMap).build();
        }
        return Result.builder().message("获取成功").status(0).success(true).data(resultMap).build();
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "退出", notes = "退出")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        redisConfig.romove(subject.getSession().getId().toString());
        //注销
        subject.logout();
        return Result.builder().message("注销成功").status(0).build();
    }

    /**
     * 修改密码
     *
     * @return
     */
    @PostMapping(value = "/updetebyPassword")
    @ResponseBody
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public Result updetebyPassword(@RequestBody UserVo uservo) {
        QueryWrapper<UserModel> userModelQueryWrapper = new QueryWrapper<UserModel>();
        userModelQueryWrapper.eq("id", uservo.getUserId());
        userModelQueryWrapper.eq("password", SecureUtil.md5(uservo.getOldPassWord()));
        UserModel user = userMapper.selectOne(userModelQueryWrapper);

        if (ObjectUtil.isNotEmpty(user) && ObjectUtil.isNotEmpty(uservo.getNewPassWord())) {
            user.setPassword(SecureUtil.md5(uservo.getNewPassWord()));
            int flag = userMapper.updateById(user);
            if (flag == 1) {
                return Result.builder().message("成功").status(0).build();
            } else {
                return Result.builder().message("修改失败").success(false).status(1).build();
            }
        }else{
            return Result.builder().message("修改失败").success(false).status(1).build();
        }

    }
}
